let ctx: CanvasRenderingContext2D | undefined | null;
export const useCanvas = () => {
  const checkCtx = (ctx: CanvasRenderingContext2D | undefined | null): ctx is CanvasRenderingContext2D => !!ctx;
  const setContext = (_ctx: CanvasRenderingContext2D | undefined | null) => {
    ctx = _ctx;
  };
  const drawRect = (x: number, y: number, width: number, height: number, color: string = "black", alpha = 1) => {
    if (!checkCtx(ctx)) return;
    ctx.globalAlpha = alpha;
    ctx.fillStyle = color;
    ctx.fillRect(x - width / 2, y - height / 2, width, height);
  };
  const drawCircle = (x: number, y: number, size: number, color: string = "black", alpha = 1) => {
    if (!checkCtx(ctx)) return;
    ctx.globalAlpha = alpha;
    ctx.beginPath();
    ctx.arc(x, y, size / 2, 0, 2 * Math.PI);
    ctx.lineWidth = 2;
    ctx.strokeStyle = color;
    ctx.stroke();
  };
  const drawRound = (x: number, y: number, size: number, color: string = "black", alpha = 1) => {
    if (!checkCtx(ctx)) return;
    ctx.globalAlpha = alpha;
    ctx.beginPath();
    ctx.arc(x, y, size / 2, 0, 2 * Math.PI);
    ctx.fillStyle = color;
    ctx.fill();
  };
  const drawImg = (x: number, y: number, width: number, height: number, img: HTMLImageElement, alpha = 1) => {
    if (!checkCtx(ctx)) return;
    ctx.globalAlpha = alpha;
    ctx.drawImage(img, x - width / 2, y - height / 2, width, height);
  };
  const clear = () => {
    if (!checkCtx(ctx)) return;
    ctx.clearRect(0, 0, window.innerWidth, window.innerWidth);
  };
  return { drawRect, drawCircle, drawRound, drawImg, clear, setContext };
};
